#include "Delay.h"

//毫秒级延时函数 bug版
void Delay_ms(uint16_t n)
{
	uint32_t tmp;
	int q = n/500, p = n%500, k = 500;
	for (int i = 0; i <= q; i++)
	{
		if (i == q)
		{
			if (p == 0)
			{
				break;
			}
			k = p;
		}
		SysTick->LOAD = SystemCoreClock/8/1000*k; //设置重装载值
		SysTick->VAL = 0x00; //把当前数值清空
		SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; //开启SysTick，开始计数
		do
		{
			tmp = SysTick->CTRL;
		}
		while((tmp&0x01) && !(tmp&(1<<16))); //等待倒数到0
		SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; //关闭SysTick，开停止计数
		SysTick->VAL = 0x00; //把当前数值清空
	}
}

void Delay_us(uint16_t n)
{
	uint32_t tmp;
	int q = n/500, p = n%500, k = 500;
	for (int i = 0; i <= q; i++)
	{
		if (i == q)
		{
			if (p == 0)
			{
				break;
			}
			k = p;
		}
		SysTick->LOAD = SystemCoreClock/8/1000000*k; //设置重装载值
		SysTick->VAL = 0x00; //把当前数值清空
		SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; //开启SysTick，开始计数
		do
		{
			tmp = SysTick->CTRL;
		}
		while((tmp&0x01) && !(tmp&(1<<16))); //等待倒数到0
		SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; //关闭SysTick，开停止计数
		SysTick->VAL = 0x00; //把当前数值清空
	}
}

